<template>
  <div class="body">
    <el-form
      :rules="rules"
      ref="loginForm"
      :model="loginForm"
      class="loginContainer"
      label-width="70px"
    >
      <h3 class="loginTitle">用户登录</h3>
      <el-form-item label="用户名:" prop="username">
        <el-input
          type="text"
          v-model="loginForm.username"
          placeholder="请输入用户名"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          placeholder="请输入密码"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="验证码:" prop="captchaId">
        <div class="codeContainer">
          <el-input
            type="text"
            auto-complete="false"
            v-model="loginForm.captchaId"
            placeholder="点击图片更换验证码"
            style="width: 250px; margin-right: 1px"
          >
          </el-input>
          <img :src="captchas || defaultCaptcha" @click="getCaptcha()" />
        </div>
      </el-form-item>
      <el-checkbox v-model="checked" class="loginRemember" @change="remember"
        >记住我</el-checkbox
      >
      <div class="Btn">
        <el-button type="primary" style="width: 75%" @click="submitLogin"
          >登录</el-button
        >
        <el-button type="primary" style="width: 75%" @click="goToRegister"
          >注册</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import { reqUserLogin, reqGetCode } from "@/api";

export default {
  name: "login",
  data() {
    return {
      defaultCaptcha: require("@/assets/captcha.png"),
      captchas: "",
      loginForm: {
        username: "",
        password: "",
        captchaId: "",
      },
      checked: true,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 14,
            message: "长度在 2 到 14 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度要大于6", trigger: "blur" },
        ],
        captchaId: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // async submitLogin() {
    //   this.$refs.loginForm.validate(async (valid) => {
    //     if (valid) {
    //       try {
    //         const redirect = this.$route.query.redirect || "/home"; // 默认跳转到/home/person
    //         const res = await reqUserLogin(this.loginForm);

    //         if (res.code === 200) {
    //           this.$message.success("登录成功");
    //           // 确保token已存储
    //           sessionStorage.setItem("token", res.data.token);

    //           // console.log(res.data);

    //           await this.$router.replace(redirect);

    //         } else {
    //           this.$message.error(res.message || "登录失败");
    //           await this.getCaptcha();
    //         }
    //       } catch (error) {
    //         console.error("登录跳转错误:", error);
    //         this.$message.error("登录过程发生异常");
    //       }
    //     }
    //   });
    // },
    async submitLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) {
          // 表单验证失败，提示用户检查输入
          this.$message.warning("请检查表单中的错误");
          return;
        }

        try {
          const { loginForm } = this;
          const redirect = this.sanitizeRedirect(this.$route.query.redirect);
          const res = await reqUserLogin(loginForm);

          if (res.code === 200) {
            this.$message.success("登录成功");
            sessionStorage.setItem("token", res.data.token);

            // 根据用户类型确定跳转路径
            const targetPath =
              res.data.user.userType === "admin" ? "/manage" : redirect;

              // console.log(targetPath);
            await this.$router.replace(targetPath);
          } else {
            this.handleLoginError(res.message);
          }
        } catch (error) {
          this.handleNetworkError(error);
        }
      });
    },

    // 方法：清理不安全的 redirect 路径
    sanitizeRedirect(path) {
      // 防止开放重定向攻击，仅允许白名单内的路径
      const allowedPaths = ["/home", "/manage"];
      return allowedPaths.includes(path) ? path : "/home";
    },

    // 方法：处理业务逻辑错误
    handleLoginError(message) {
      this.$message.error(message || "登录失败");
      this.getCaptcha(); // 刷新验证码
    },

    // 方法：处理网络或未知错误
    handleNetworkError(error) {
      console.error("登录失败:", error);
      this.$message.error("网络异常，请检查连接后重试");
      this.getCaptcha(); // 可选：刷新验证码
    },
    goToRegister() {
      this.$router.push("/register");
    },
    async getCaptcha() {
      const res = await reqGetCode();

      if (res.code === 200) {
        this.captchas = res.data.captchaImage;
        this.$message.success("验证码获取成功");
      } else {
        this.$message.error("验证码获取失败");
      }
    },
    remember(checked) {
      if (checked) {
        localStorage.setItem("username", this.loginForm.username);
        localStorage.setItem("password", this.loginForm.password);
      } else {
        localStorage.removeItem("username");
        localStorage.removeItem("password");
      }
    },
  },
  mounted() {
    // 页面加载时检查localStorage中是否有保存的用户名和密码
    this.loginForm.username = localStorage.getItem("username") || "";
    this.loginForm.password = localStorage.getItem("password") || "";
    // 如果有保存的信息，则默认勾选复选框
    if (this.loginForm.username && this.loginForm.password) {
      this.checked = true;
    }
    this.getCaptcha();
  },
};
</script>

<style lang="scss" scoped>
/* 页面主体样式 */
.body {
  width: 100vw;
  /* 视窗宽度的100% */
  height: 100vh;
  /* 视窗高度的100% */
  background-image: url("@/assets/background1.png");
  background-size: 100%;
  /* 背景图片大小 */
  overflow: hidden;
  /* 隐藏溢出内容 */
}

/* 登录容器样式 */
.loginContainer {
  border-radius: 15px;
  /* 圆角边框 */
  background-clip: padding-box;
  /* 背景剪裁至内400 */
  text-align: left;
  /* 文本左对齐 */
  margin: auto;
  /* 上下左右居中 */
  margin-top: 180px;
  /* 容器顶部外边距 */
  width: 350px;
  /* 固定宽度 */
  padding: 15px 35px;
  /* 内边距 */
  background: aliceblue;
  /* 背景颜色 */
  border: 1px solid #efefef;
  /* 边框 */
  box-shadow: 0 0 25px #efefef;

  /* 阴影效果 */
  /* 登录标题样式 */
  .loginTitle {
    margin: 0px auto 48px auto;
    /* 自动调整左右外边距，底部外边距为48px */
    text-align: center;
    /* 文本居中 */
    font-size: 40px;
    /* 字体大小 */
  }

  /* 记住我选项样式 */
  .loginRemember {
    text-align: left;
    /* 文本左对齐 */
    margin: 0px 0px 15px 0px;
    /* 底部外边距为15px */
  }

  .Btn {
    display: flex;
    justify-content: space-around;
  }
}

// 验证码样式
.codeContainer {
  display: flex;
  flex-wrap: nowrap;

  img {
    width: 150px;
    height: 40px;
  }
}

.el-form-item__label {
  font-size: 12px;
}
</style>
